package com.example.administrator.im.ui.activity;

import android.annotation.TargetApi;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.im.R;
import com.example.administrator.im.db.FriendDBHelper;
import com.example.administrator.im.db.GroupDBHelper;
import com.example.administrator.im.json.FriendJson;
import com.example.administrator.im.json.ResultJson;
import com.example.administrator.im.service.MsgListenerService;
import com.example.administrator.im.ui.fragment.IMFragment;
import com.example.administrator.im.ui.fragment.LinkmanFragment;
import com.example.administrator.im.ui.fragment.MyFragment;
import com.example.administrator.im.utils.EMUtils;
import com.example.administrator.im.utils.HttpUtils;
import com.example.administrator.im.utils.NotificationUtils;
import com.google.gson.Gson;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.util.NetUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static java.lang.Thread.sleep;

/**
 * create:2018/10/2 16:15
 * author: 姚鸿杰
 **/
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "HomeActivity";

    //底部控件的数量
    private final int nav_count = 3;

    //选中的图标
    private int icon_c[] = new int[]{
            R.mipmap.imf, R.mipmap.linkmanf, R.mipmap.myf
    };

    //未选中的图标
    private int icon[] = new int[]{
            R.mipmap.im, R.mipmap.linkman, R.mipmap.my
    };

    //底部控件
    private LinearLayout[] ll_nav = new LinearLayout[nav_count];

    //底部控件图标
    private ImageView[] iv_nav = new ImageView[nav_count];

    //底部控件字体
    private TextView tv_nav[] = new TextView[nav_count];

    //当前点击第几个底部控件
    private static int num = 0;
    private boolean isRecycle = false;  //判断软件是否被系统回收

    private TextView msg_cnt;   //显示未读总数

    private static boolean isSearchFriend = false;

    private Fragment[] fragment = new Fragment[nav_count];

    private static final String IM_FRAGMENT_KEY = "IMFragment";
    private static final String ADDRESS_BOOK_FRAGMENT_KEY = "LinkmanFragment";
    private static final String MY_FRAGMENT_KEY = "MYFragment";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        getWindow().setStatusBarColor(Color.TRANSPARENT);

        SharedPreferences spf = getSharedPreferences("user", Context.MODE_PRIVATE);
        boolean isLogin = spf.getBoolean("isLogin", false);
        if (!isLogin) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
        setContentView(R.layout.activity_home);

        isSearchFriend = false;
        if (isLogin) {
            EMUtils.getGroups();
            initFriends();
        }


        setNotification();

        initView();
        setListener();
        savedInstance(savedInstanceState);

        isRecycle = false;
        startService();
        EventBus.getDefault().register(this);
        //注册一个监听连接状态的listener
        EMClient.getInstance().addConnectionListener(new MyConnectionListener());
        Log.e(TAG, "onCreate");
    }

    public static boolean isIsSearchFriend() {
        return isSearchFriend;
    }

    private void initFriends() {

        if (LitePal.findAll(GroupDBHelper.class).size() == 0) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        sleep(200);
                        initFriends();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {

            final List<FriendDBHelper> friends = LitePal.findAll(FriendDBHelper.class);

            //如果数据库没数据
            if (friends.size() == 0) {
                //从web端获取数据
                HttpUtils.getFriendsRequest(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e(TAG, e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String content = response.body().string();
                        Gson gson = new Gson();
                        ResultJson json = gson.fromJson(content, ResultJson.class);
                        if (json.getCode() == HttpUtils.SUCCESS) {
                            FriendJson friendJson = gson.fromJson(content, FriendJson.class);
                            isSearchFriend = true;
                            int count = friendJson.getData().size();
                            if (count <= 0) {
                                return;
                            }
                            //存储好友
                            for (int i = 0; i < count; i++) {
                                FriendJson.FriendsJson ffj = friendJson.getData().get(i);

                                if (LitePal.where("username = ?", ffj.getUsername())
                                        .findFirst(FriendDBHelper.class) != null) {
                                    continue;
                                }

                                FriendDBHelper friend = new FriendDBHelper();

                                friend.setUsername(ffj.getUsername());  //保存账号
                                friend.setNickname(ffj.getNickname());  //保存昵称
                                friend.setRemarks(ffj.getRemarks());    //备注
                                friend.setImg_path(ffj.getImg_path());  //图片路径
                                friend.setDisturb(ffj.isDisturb()); //是否消息免打扰
                                friend.setSignature(ffj.getSignature());    //个性签名
                                int position = ffj.getPosition();
                                GroupDBHelper group = LitePal.where("position = ?", String.valueOf(position)).findFirst(GroupDBHelper.class);
                                friend.setGroup_id(group.getId());
                                friend.save();
                            }
                            if (fragment[1] != null) {
                                EventBus.getDefault().post(new LinkmanFragment.UpdateExpandableListViewData());
                            }

                            EventBus.getDefault().post(new IMFragment.UpdateIMConversations());

                        } else if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                            Log.e(TAG, json.getData().toString());
                        }
                    }
                });
            }
        }
    }

    private static boolean isHasNetwork = false;

    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() { //链接到服务器时调用

            if (isHasNetwork)
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        EMUtils.getGroups();
                        initFriends();
                        isHasNetwork = false;
                    }
                });
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        // 显示帐号已经被移除
                    } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
                        Toast.makeText(HomeActivity.this, "帐号在其他设备登录", Toast.LENGTH_SHORT).show();
                        EMUtils.logout(HomeActivity.this);
                        //弹出提示框，是否重新登录

                        //重新登录时最好重新获取数据

                    } else {
                        if (NetUtils.hasNetwork(HomeActivity.this)) {
                            //连接不到聊天服务器
                        } else {
                            //当前网络不可用，请检查网络设置
                            Toast.makeText(HomeActivity.this, "当前网络不可用，请检查网络设置", Toast.LENGTH_SHORT).show();
                            isHasNetwork = true;
                            //弹出吐司
                        }
                    }
                }
            });
        }
    }


    /**
     * 设置Android8.0通知
     */
    private void setNotification() {
        //Android8.0通知
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = NotificationUtils.CHAT_CHANNEID;
            String channelName = NotificationUtils.CHAT_CHANNENAME;
            int importance = NotificationUtils.CHAT_IMPORTANCE;
            createNotificationChannel(channelId, channelName, importance);

            channelId = NotificationUtils.SUBSCRIBE_CHANNEID;
            channelName = NotificationUtils.SUBSCRIBE_CHANNENAME;
            importance = NotificationUtils.SUBSCRIBE_IMPORTANCE;
            createNotificationChannel(channelId, channelName, importance);
        }
    }

    /**
     * 获取保存的fragment  没有的话返回null
     */
    private void savedInstance(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            /*获取保存的fragment  没有的话返回null*/
            fragment[0] = (IMFragment) getSupportFragmentManager().getFragment(savedInstanceState, IM_FRAGMENT_KEY);
            fragment[1] = (LinkmanFragment) getSupportFragmentManager().getFragment(savedInstanceState, ADDRESS_BOOK_FRAGMENT_KEY);
            fragment[2] = (MyFragment) getSupportFragmentManager().getFragment(savedInstanceState, MY_FRAGMENT_KEY);

            bottom_animation(num, true);
        } else {
            initFragment(0);
            //初始化图标
            bottom_animation(0, true);
            iv_nav[1].setImageResource(icon[1]);
            iv_nav[2].setImageResource(icon[2]);
        }
    }

    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        NotificationManager notificationManager = (NotificationManager) getSystemService(
                NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
    }

    /**
     * 启动服务
     */
    private void startService() {
        Intent intent = new Intent(this, MsgListenerService.class);
        startService(intent);
    }

    /**
     * 设置监听事件
     */
    private void setListener() {
        ll_nav[0].setOnClickListener(this);
        ll_nav[1].setOnClickListener(this);
        ll_nav[2].setOnClickListener(this);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        ll_nav[0] = (LinearLayout) findViewById(R.id.im_nav);
        ll_nav[1] = (LinearLayout) findViewById(R.id.address_nav);
        ll_nav[2] = (LinearLayout) findViewById(R.id.my_nav);

        iv_nav[0] = (ImageView) findViewById(R.id.iv_im);
        iv_nav[1] = (ImageView) findViewById(R.id.iv_address);
        iv_nav[2] = (ImageView) findViewById(R.id.iv_my);

        tv_nav[0] = (TextView) findViewById(R.id.tv_im);
        tv_nav[1] = (TextView) findViewById(R.id.tv_address);
        tv_nav[2] = (TextView) findViewById(R.id.tv_my);

        msg_cnt = (TextView) findViewById(R.id.msg_cnt);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.im_nav:
                bottom_animation(0, false);
                initFragment(0);
                break;
            case R.id.address_nav:
                bottom_animation(1, false);
                initFragment(1);
                break;
            case R.id.my_nav:
                bottom_animation(2, false);
                initFragment(2);
                break;
        }
    }

    /**
     * 初始化fragment
     *
     * @param flag 第几个fragment
     */
    private void initFragment(int flag) {

        //开启事务，fragment的控制是由事务来实现
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (fragment[flag] == null) {
            switch (flag) {
                case 0:
                    fragment[flag] = new IMFragment();
                    break;
                case 1:
                    fragment[flag] = new LinkmanFragment();
                    break;
                case 2:
                    fragment[flag] = new MyFragment();
                    break;
            }
            /*判断该fragment是否已经被添加过  如果没有被添加  则添加*/
            if (!fragment[flag].isAdded()) {
                /*添加到 fragmentList*/
                transaction.add(R.id.home_fragment, fragment[flag]);
            }

        }

        //隐藏所有fragment
        hideFragment(transaction);
        //显示点中的fragment
        transaction.show(fragment[flag]);

        transaction.commit();
    }

    /**
     * 隐藏所有fragment
     *
     * @param transaction 事务
     */
    private void hideFragment(FragmentTransaction transaction) {
        for (int i = 0; i < nav_count; i++) {
            if (fragment[i] != null) {
                transaction.hide(fragment[i]);
            }
        }
    }


    /**
     * 底部控件选中的动画
     *
     * @param num 选中的下标
     */
    private void bottom_animation(int num, boolean isInit) {

        if (this.num == num && !isInit) {
            this.num = num;
            return;
        }

        for (int i = 0; i < ll_nav.length; i++) {
            if (i == num) { //选中的fragment
                iv_nav[i].setImageResource(icon_c[i]);

                ScaleAnimation sak = new ScaleAnimation(1f, 1.1f, 1f, 1.1f,
                        Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                sak.setDuration(500);
                sak.setFillAfter(true);
                ll_nav[i].startAnimation(sak);

                tv_nav[i].setTextColor(getResources().getColor(R.color.theme_color));
            } else if (i == this.num) { //未选中的fragment
                iv_nav[i].setImageResource(icon[i]);

                ScaleAnimation sas = new ScaleAnimation(1.1f, 1f, 1.1f, 1f,
                        Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                sas.setDuration(500);
                sas.setFillAfter(true);
                ll_nav[i].startAnimation(sas);

                tv_nav[i].setTextColor(getResources().getColor(R.color.default_color));
            } else {
                iv_nav[i].setImageResource(icon[i]);
            }
        }

        this.num = num;
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {

        /*fragment不为空时 保存*/
        if (fragment[0] != null) {
            getSupportFragmentManager().putFragment(outState, IM_FRAGMENT_KEY, fragment[0]);
        }
        if (fragment[1] != null) {
            getSupportFragmentManager().putFragment(outState, ADDRESS_BOOK_FRAGMENT_KEY, fragment[1]);
        }
        if (fragment[2] != null) {
            getSupportFragmentManager().putFragment(outState, MY_FRAGMENT_KEY, fragment[2]);
        }

        isRecycle = true;
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume");
        setIsAckedCount();
    }

    private void setIsAckedCount() {
        int count = EMUtils.getisAckedCount();
        if (count == 0) {
            msg_cnt.setVisibility(View.GONE);
        } else {
            msg_cnt.setVisibility(View.VISIBLE);
            msg_cnt.setText(String.valueOf(count));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateIsAckedCount(UpdateIsAckedCount updateIsAckedCount) {
        setIsAckedCount();
    }

    public static class UpdateIsAckedCount {
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy");
        if (!isRecycle) {
            num = 0;
        }
//        stopService(new Intent(this, MsgListenerService.class));
        EventBus.getDefault().unregister(this);
    }
}
